package yawning.mew.cat;

import yawning.mew.ProcEffect.Trigger;
import yawning.mew.cat.CatModelSimulation.SimulatorProperty;
import yawning.mew.character.CharacterModel.AttackResult;
import yawning.mew.character.Druid.Glyph;
import yawning.mew.sim.SimulationAction;
import yawning.mew.sim.SimulationEventAction;

public class EventMangleDebuff extends SimulationEventAction {
	private boolean mExternalDebuff;
	CatModelSimState mState;

	EventMangleDebuff(CatModelSimState state) {
		super(state.mSimUtil);
		mState = state;
		mExternalDebuff = mState.mSimUtil.getConfig().getBool(SimulatorProperty.ASSUMEEXTERNALMANGLE);
		if (mExternalDebuff) schedule(Double.MAX_VALUE);
	}

	@Override
	public double perform() {
		int cost = mState.getEnergyCost(mState.mModel.mangleCost);
		if (mState.energyTickEv.mEnergy < cost && !mState.oocEv.isUp()) return SimulationAction.ACTION_FAIL;

		AttackResult result = mState.mModel.getYellowResult();

		if (mState.mDebug) mState.DBGF("Mangle (%s)", result);

		if (result == AttackResult.MISS) {
			cost = (int) Math.round(cost * 0.2);
			mState.nrMangleMiss++;
		} else if (result == AttackResult.DODGE) {
			cost = (int) Math.round(cost * 0.2);
			mState.nrMangleDodge++;
		} else {
			double damage = mState.mModel.getWeaponDamage() * mState.mModel.levelDep.getMangleMult() + mState.mModel.levelDep.getMangleDmg();
			damage *= ((mState.mModel.druid.hasGlyph(Glyph.MANGLE)) ? 1.1 : 1);

			if (result == AttackResult.CRIT) {
				mState.nrMangleCrit++;
				damage *= mState.mModel.multCrit;
				mState.mSimUtil.triggerProc(Trigger.YELLOWCRIT);
			} else {
				mState.nrMangleHit++;
				mState.mSimUtil.triggerProc(Trigger.YELLOW);
			}

			damage *= mState.getDirectDamageMult();
			mState.mangleDamage += Math.round(damage);

			if (mState.mDebug) mState.DBGF("  Damage: %d", Math.round(damage));

			if (!mExternalDebuff) schedule(mState.mModel.mangleDebuffDuration);

			if (mState.mModel.druid.tier_11_4pc) {
				mState.tier_11_4pcEv.run();
				if (mState.mDebug) mState.DBGF("  Tier 11 Stack: %f (%f)", mState.mModel.tier_11_4pc_buffStacks, mState.tier_11_4pcEv.getExpiryTime());
			}

			mState.onCpGenerator(result == AttackResult.CRIT);
		}

		mState.onOoCConsumer(cost);

		return 1.0;
	}

	@Override
	public void onExpire() {
		if (mState.mDebug) mState.DBGF("Mangle Expiration");
	}
}
